package store.wetravel.web.user.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import store.wetravel.common.Const;
import store.wetravel.common.ServerResponse;
import store.wetravel.common.TokenCache;
import store.wetravel.util.MD5Util;
import store.wetravel.web.user.mapper.UserMapper;
import store.wetravel.pojo.User;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * Created by xinlong on 2017/10/14.
 */
@Service("iUserService")
public class UserServiceImpl implements IUserService{

    @Resource(name="userMapper")
    UserMapper userMapper;

    public ServerResponse<String> resetPassword(String username,String password,String tokenCache){
        ServerResponse response = this.checkValid(username,Const.USERNAME);
        //如果通过为空的校验
        if(response.isSuccess()){
            return ServerResponse.createByErrorMessage("该用户不存在");
        }
        if(StringUtils.isBlank(password)||StringUtils.isBlank(tokenCache)){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);
        if(StringUtils.isBlank(token)){
            return ServerResponse.createByErrorMessage("token无效或者过期");
        }
        if(StringUtils.equals(tokenCache,token)){
            String md5Password = MD5Util.MD5EncodeUtf8(password);
            int rowCount = userMapper.updatePasswordByUsername(username,md5Password);
            if(rowCount > 0){
                return ServerResponse.createBySuccessMessage("修改密码成功");
            }
        }else{
            return ServerResponse.createByErrorMessage("token错误，请重新获取重置密码的token");
        }
        return ServerResponse.createByErrorMessage("修改密码失败");

    }

    public ServerResponse<String> checkAnswer(String username,String question,String answer){
        ServerResponse response = this.checkValid(username,Const.USERNAME);
        //如果通过为空的校验
        if(response.isSuccess()){
            return ServerResponse.createByErrorMessage("该用户不存在");
        }
        if(StringUtils.isBlank(question)||StringUtils.isBlank(question)){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        String result = userMapper.forgetGetQuestion(username);
        if(StringUtils.isBlank(result)){
            return ServerResponse.createByErrorMessage("找回密码的问题是空的");
        }
        int resultCount = userMapper.checkAnswer(username,question,answer);
        //验证通过
        if(resultCount>0){
            //说明问题及问题答案是这个用户的，并且是正确的
            String tokenCache = UUID.randomUUID().toString();
            TokenCache.SetKey(TokenCache.TOKEN_PREFIX+username,tokenCache);
            return ServerResponse.createBySuccess(tokenCache);
        }
        return ServerResponse.createByErrorMessage("回答错误");
    }

    public ServerResponse<String> forgetGetQuestion(String username){
        ServerResponse resultCount = this.checkValid(username,Const.USERNAME);
        //如果通过为空的校验
        if(resultCount.isSuccess()){
            return ServerResponse.createByErrorMessage("该用户不存在");
        }
        System.out.println(username);
        String result = userMapper.forgetGetQuestion(username);
        System.out.println("question:"+result);
        if(StringUtils.isNotBlank(result)){
            return ServerResponse.createBySuccess(result);
        }
        return ServerResponse.createByErrorMessage("找回密码的问题是空的");
    }

    public ServerResponse<User> login(String username,String password){
        int resultCount = userMapper.checkUsername(username);
        if(resultCount == 0){
            return ServerResponse.createByErrorMessage("用户名不存在");
        }

        String md5Password = MD5Util.MD5EncodeUtf8(password);
        User user = userMapper.selectLogin(username,md5Password);
        if(user == null){
            System.out.println("username="+username);
            System.out.println("password="+password);
            return ServerResponse.createByErrorMessage("密码错误");
        }
        user.setPassword(StringUtils.EMPTY);

        return ServerResponse.createBySuccess("登录成功",user);
    }

    public ServerResponse<String> register(User user){
        ServerResponse validResponse = this.checkValid(user.getUsername(),Const.USERNAME);
        if(!validResponse.isSuccess()){
            return validResponse;
        }
        validResponse = this.checkValid(user.getEmail(),Const.EMAIL);
        if(!validResponse.isSuccess()){
            return validResponse;
        }
        //赋予用户权限
        user.setRole(Const.Role.ROLE_CUSTOMER);
        //MD5加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        int resultCount = userMapper.insert(user);
        if(resultCount == 0){
            return ServerResponse.createByErrorMessage("注册失败");
        }
        return ServerResponse.createBySuccessMessage("注册成功");
    }

    public ServerResponse<String> checkValid(String str,String type){
        if(StringUtils.isNotBlank(str)){
            if(Const.USERNAME.equals(type)){
                int rowCount = userMapper.checkUsername(str);
                if(rowCount > 0){
                    return ServerResponse.createByErrorMessage("用户名已存在");
                }
            }
            if(Const.EMAIL.equals(type)){
                int rowCount = userMapper.checkEmail(str);
                if(rowCount > 0){
                    return ServerResponse.createByErrorMessage("Email已存在");
                }
            }
            if(Const.PHONE.equals(type)){
                int rowCount = userMapper.checkPhone(str);
                if(rowCount > 0){
                    return ServerResponse.createByErrorMessage("电话号码已存在");
                }
            }
        } else{
            return ServerResponse.createByErrorMessage("参数为空!");
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }

    public ServerResponse<User> updateInformation(User user){
        //username不能被更新
        //email也要进行校验，校验新的email是否已经存在，并且存在的email如果相同的话，不能是我们当前的这个用户
        int resultCount = userMapper.checkEmailByUserId(user.getEmail(),user.getId());
        if(resultCount > 0){
            return ServerResponse.createByErrorMessage("email已存在，请更换email再尝试更新");
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());

        int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);
        if(updateCount > 0){
            return ServerResponse.createBySuccess("更新个人信息成功",updateUser);
        }
        return ServerResponse.createByErrorMessage("更新个人信息失败");
    }

    public ServerResponse<User> getInformation(Integer userId){
        User user = userMapper.selectByPrimaryKey(userId);
        if(user == null){
            return ServerResponse.createByErrorMessage("找不到当前用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }

    //backend

    /**
     * 校验是否是管理员
     * @param user
     * @return
     */
    public ServerResponse checkAdminRole(User user){
        if(user != null && user.getRole().intValue() == Const.Role.ROLE_ADMIN){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }

}
